﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace com.lib.net
{

    /// <summary>
    /// 丢包,处理
    /// </summary>
   public class MessageStream
    {
        //消息头 125 byte 消息长度 4字节 byte[]数组 int  消息号: byte 1字节   消息体 字节数组

        private byte[] _buffer;
        private int _position;
        private int _length;
        private int _capacity;

       public MessageStream()
       {
           _buffer = new byte[0];
           _position = 0;
           _length = 0;
           _capacity = 0;

       }

       public void Write(byte[] buffer, int offset, int count)
       {
           if (buffer.Length - offset < count)
           {
               count = buffer.Length - offset;
           }
           EnsureCapacity(_length + count);
           Array.Clear(_buffer, _length, _capacity - _length);
           Buffer.BlockCopy(buffer, offset, _buffer, _length, count);
           _length += count;
       }

       /// <summary>
       /// 获取消息Byte 字节
       /// </summary>
       public Message ReadData()
       {
           byte id = 0;
           int len = 0;
           byte[] data = null;
           for (int i = 0; i < _buffer.Length; i++)
           {
               if (_buffer[i] == 125)
               {
                   id = _buffer[i + 1];
                   byte [] msglen = new byte[4];
                   for (int j = 0; j < msglen.Length; j++)
                   {
                       msglen[j] = _buffer[i+2+j];
                   }
                   len = BitConverter.ToInt32(msglen,0);
                   data = new byte[len-6];
                   Array.Copy(_buffer, i + 6, data,0, data.Length); //总长度-6 获取的消息提长度
                   Array.Clear(_buffer, i, len); //移除缓冲区
                   break;
               }
           }
           if (id == 0)
           {
               return null;
           }
           _length -= len;
           Message message = new Message();
           message._id = id;
           message._content = data;
           //移除数据
           return message;
       }


       public bool Read(out Message message)
       {
           message = null;
           _position = 0;
           if (_length <= 6)
           {
               return false;
           }
           message = ReadData();
           return true;
       }


       /// <summary>
       /// 根据原有的长度加上新读来的长度创建缓冲区
       /// </summary>
       /// <param name="value"></param>
       private void EnsureCapacity(int value)
       {
           if (value <= _capacity)
               return;
           var num1 = value;
           if (num1 < 0x100)// int 256
               num1 = 0x100;
           if (num1 < (_capacity * 2))
               num1 = _capacity * 2;
           var buffer1 = new byte[num1];
           if (_length > 0)
               Buffer.BlockCopy(_buffer, 0, buffer1, 0, _length);
           _buffer = buffer1;
           _capacity = num1;
       }

    }
}
